
package com.monlyu.dao;

import org.hibernate.Criteria;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.monlyu.bean.Page;
import com.monlyu.bean.Pages;
import com.monlyu.util.LogUtil;
import com.monlyu.util.VarParamUtil;
import com.monlyu.util.WebOptUtil;
import com.monlyu.vo.User;

public abstract class BaseDao {

    protected Dao dao;
    private SqlDao sqlDao;

    public void setSqlDao(SqlDao sqlDao){
        this.sqlDao = sqlDao;
    }

    public void setDao(Dao dao){
        this.dao = dao;
    }

    /**
     * 获取当前用户
     * 
     * @return 可以在Bo层 或Dao层直接使用该参数
     */
    protected User curUser(){
        final User user = WebOptUtil.curUser();
        if (user == null) {
            return null;
        }
        return user;
        // return dao.get(User.class, user.getId());
    }

    protected User admin(){
        return dao.get(User.class, 1l);
    }

    /**
     * 创建
     * 
     * @author monlyu
     * @since 2010-1-13
     */
    protected <T> Pages<T> buildPages(Page page, Criteria criteria, String... matches){
        if (page.getStore() != null) {
            criteria.addOrder(page.isAsc() ? Order.asc(page.getStore()) : Order.desc(page.getStore()));
        }
        if (page.getKey() != null && (!VarParamUtil.isEmpty(matches))) {
            Criterion fuzzy = null;
            for (int i = 0; i < matches.length; i++) {
                final Criterion find = Restrictions.like(matches[i], page.getKey(), MatchMode.ANYWHERE);
                if (fuzzy == null) {
                    fuzzy = find;
                } else {
                    fuzzy = Restrictions.or(fuzzy, find);
                }
            }
            criteria.add(fuzzy);
        }
        return findByCriteria(page.getNo(), page.getSize(), criteria);
    }

    /**
     * 通过Criteria来进行查询 统计总行数 Integer count = criteria.list().size();
     * 这种方法统计出来的结果如果太大,则直接报告内存溢出
     * 
     * @since 2010-1-13
     */
    @SuppressWarnings("unchecked")
    public <T> Pages<T> findByCriteria(final int pageNo, int pageSize, Criteria criteria){
        Pages<T> pages = null;
        try {
            Integer count = dao.countRow(criteria);
            criteria.setFirstResult(pageNo * pageSize);
            criteria.setMaxResults(pageSize);
            pages = new Pages(criteria.list(), count, pageNo);
        }
        catch (Exception e) {
            LogUtil.logWithTime(BaseDao.class, "请求查询分页时发生异常" + e);
        }
        return pages;
    }
}
